<template>
	<view class="container position-relative">
		<view style="margin-bottom: 130rpx;">
			<view class="section-1">
				<list-cell>
					<view class="d-flex align-items-center justify-content-between mb-10">
						<image src="/static/images/map.png" class="scan-icon-left"></image>
					</view>
					<view class="w-100 d-flex flex-column" style="margin-left: 10rpx;font-size: 32rpx;">
						<view class="d-flex align-items-center justify-content-between mb-10 input-item">
							<input 
								class="input-field" 
								type="text" 
								v-model="address.name" 
								placeholder="请输入姓名"
								maxlength="20"
							/>
							<input 
								class="input-field" 
								type="number" 
								v-model="address.mobile" 
								placeholder="请输入手机号"
								maxlength="11"
							/>
						</view>
						<view class="d-flex" style="margin-top:8rpx;font-size: 28rpx;">
							<view class="address-info text-color-assist font-size-base" v-if="address.scanAddress">{{ address.scanAddress }}</view>
							<view class="font-size-lg text-color-base" v-else>请扫码获取地址</view>
						</view>
					</view>
					<view class="d-flex" @click="scanToGetAddress">
						<image src="/static/images/scan-icon.png" class="scan-icon-left"></image>
					</view>
				</list-cell>
			</view>

			<view class="section-1">
				<list-cell class="location">
					<view class="flex-fill d-flex justify-content-between align-items-center">
						<view class="store-name flex-fill">{{ store.name }}{{ table.name ? '-' + table.name : '' }}</view>
					</view>
				</list-cell>
				<list-cell arrow class="meal-time" v-if="orderType == 'takein'">
					<view class="flex-fill d-flex justify-content-between align-items-center"
						@click="takeinTIme = !takeinTIme">
						<view class="title">取餐时间</view>
						<view class="time">
							{{ takeinRange[defaultSelector[0]].name }}
							<u-picker v-model="takeinTIme" :range="takeinRange" range-key="name" mode="selector"
								@cancel="takeinCancelTime" @confirm="takeinConfirmTime"
								:default-selector="defaultSelector"></u-picker>
						</view>
					</view>
				</list-cell>
				<list-cell class="contact" last :hover="false" v-if="orderType == 'takein'">
					<view class="flex-fill d-flex justify-content-between align-items-center">
						<view class="title flex-fill">联系电话</view>
						<view class="time"><input class="text-right" placeholder="请输入手机号码" v-model="address.mobile" />
						</view>
						<button class="contact-tip font-size-sm" @click="fillContact">自动填写</button>
					</view>
				</list-cell>
				<list-cell class="contact" last :hover="false" v-if="orderType == 'takein'">
					<view class="flex-fill d-flex justify-content-between align-items-center">
						<view class="title flex-fill">联系电话</view>
						<view class="time"><input class="text-right" placeholder="请输入手机号码" v-model="address.mobile" />
						</view>
						<button class="contact-tip font-size-sm" @click="fillContact">自动填写</button>
					</view>
				</list-cell>
			</view>
			<!-- 购物车列表 begin -->
			<view class="section-2">
				<view class="cart d-flex flex-column">
					<list-cell last v-for="(item, index) in cart" :key="index">
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center mb-10">
								<view
									class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<image style="width: 80rpx;height: 80rpx;" mode="aspectFill" :src="item.image">
									</image>
								</view>
								<view class="name-and-props overflow-hidden">
									<view class="text-color-base font-size-lg">{{ item.name }}</view>
								</view>
								<view
									class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<view>x{{ item.number }}</view>
									<view>￥{{ item.sales_price }}</view>
								</view>
							</view>
							<view class="text-truncate font-size-base text-color-assist">{{ item.props_text }}</view>
						</view>
					</list-cell>
				</view>
				<list-cell last>
					<view class="flex-fill d-flex justify-content-end align-items-center">
						<view>
							总计￥{{ total }}
							<text v-if="coupon.value">,￥-{{ coupon.value }}</text>
							, 实付
						</view>
						<view class="font-size-extra-lg font-weight-bold">￥{{ amount }}</view>
					</view>
				</list-cell>
			</view>
			<!-- 支付方式 begin -->
			<view class="payment">
				<list-cell last :hover="false"><text>支付方式</text></list-cell>
				<list-cell>
					<view class="d-flex align-items-center justify-content-between w-100"
						:class="{disabled: member.money < amount}" @click="setPayType(2)">
						<view class="iconfont iconbalance line-height-100 payment-icon"></view>
						<view class="flex-fill">余额支付（账户余额￥{{ member.money }}）</view>
						<view class="font-size-sm" v-if="member.money < amount">余额不足</view>
						<view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType == 2">
						</view>
						<view class="iconfont line-height-100 checkbox iconradio-button-off" v-else></view>
					</view>
				</list-cell>
				<list-cell last>
					<view class="d-flex align-items-center justify-content-between w-100" @click="setPayType(1)">
						<view class="iconfont iconwxpay line-height-100 payment-icon" style="color: #7EB73A"></view>
						<view class="flex-fill">微信支付</view>
						<view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType == 1">
						</view>
						<view class="iconfont line-height-100 checkbox iconradio-button-off" v-else></view>
					</view>
				</list-cell>
			</view>
			<!-- 备注 begin -->
			<list-cell arrow last @click="goToRemark">
				<view class="d-flex flex-fill align-items-center justify-content-between overflow-hidden">
					<view class="flex-shrink-0 mr-20">备注</view>
					<view class="text-color-primary flex-fill text-truncate text-right">{{ form.remark || '点击填写备注' }}
					</view>
				</view>
			</list-cell>
			<!-- 付款栏 begin -->
			<view style="z-index: 1;margin-bottom: 50rpx;"
				class="w-100 pay-box position-fixed fixed-bottom d-flex align-items-center justify-content-between bg-white">
				<view class="font-size-sm" style="margin-left: 20rpx;">合计：</view>
				<view class="font-size-lg flex-fill">￥{{ amount }}</view>
				<view class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base"
					style="padding: 0 60rpx;" @tap="$u.debounce(submit, 500)">立即付款</view>
			</view>
			<!-- 确认模态框 -->
			<modal :show="ensureAddressModalVisible" custom :mask-closable="false" :radius="'20rpx'" width="90%">
				<view class="modal-content">
					<view class="d-flex justify-content-end">
						<image src="/static/images/pay/close.png" style="width: 40rpx; height: 40rpx;"
							@tap="ensureAddressModalVisible = false"></image>
					</view>
					<view class="d-flex just-content-center align-items-center" style="margin-bottom: 40px;">
						<view class="font-size-extra-lg text-color-base">请再次确认下单信息</view>
					</view>
					<view
						class="d-flex font-size-base text-color-base font-weight-bold align-items-center justify-content-between mb-20">
						<view>{{ address.name }} {{ address.sex ? '女士' : '先生' }}</view>
						<view>{{ address.mobile }}</view>
					</view>
					<view class="d-flex font-size-sm text-color-assist align-items-center justify-content-between mb-40">
						<view style="max-width: 60%;">{{ address.scanAddress }}</view>
						<button type="primary" size="mini" plain class="change-address-btn" style="white-space: nowrap;"
							@click="scanToGetAddress">重新扫码</button>
					</view>
					<button type="primary" class="pay_btn" @tap="$u.debounce(pay, 500)">确认并付款</button>
				</view>
			</modal>
		</view>
	</view>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex';
import listCell from '@/components/list-cell/list-cell';
import modal from '@/components/modal/modal';
// #ifdef H5
var jweixin = require('jweixin-module');
// #endif

export default {
	components: {
		listCell,
		modal
	},
	data() {
		return {
			cart: [],
			form: {
				remark: ''
			},
			ensureAddressModalVisible: false,
			takeoutTIme: false,
			paramsTime: {
				year: false,
				month: false,
				day: false,
				hour: true,
				minute: true,
				second: false
			},
			defaultTime: '00:00',
			takeinTIme: false,
			takeinRange: [
				{ name: '立即用餐', value: 0 },
				{ name: '10分钟后', value: 10 },
				{ name: '20分钟后', value: 20 },
				{ name: '30分钟后', value: 30 },
				{ name: '40分钟后', value: 40 },
				{ name: '50分钟后', value: 50 }
			],
			defaultSelector: [0],
			payType: 1, // 1=微信支付, 2=余额支付
			coupons: 0,
			coupon: {},
			subscribeMss: {
				'takein': '',
				'takeout': '',
				'takein_made': '',
				'takeout_made': ''
			},
			address: {
				name: '',
				mobile: '',
				sex: 0,
				scanAddress: '',
				address_id: ''
			},
			cart_ids: [] 
		};
	},
	computed: {
		...mapState(['orderType', 'store', 'member', 'table']),
		total() {
			return this.cart.reduce((acc, cur) => acc + cur.number * cur.sales_price, 0);
		},
		amount() {
			let amount = this.cart.reduce((acc, cur) => acc + cur.number * cur.sales_price, 0);
			if (this.coupon.hasOwnProperty('id')) {
				amount -= parseFloat(this.coupon.value);
			}
			return amount.toFixed(2);
		}
	},
	onShow() {
		let date = new Date(new Date().getTime() + 3600000);
		let hour = date.getHours();
		let minute = date.getMinutes();
		if (hour < 10) {
			hour = '0' + hour;
		}
		if (minute < 10) {
			minute = '0' + minute;
		}
		this.defaultTime = hour + ':' + minute;

		let paytype = uni.getStorageSync('paytype');
		this.payType = paytype ? paytype : 1;
	},
	onLoad(option = {}) {
		const { remark, address_detail } = option;
		this.cart = uni.getStorageSync('cart') || [];
		remark && this.$set(this.form, 'remark', remark);
		if (address_detail) {
			this.address.scanAddress = decodeURIComponent(address_detail);
			this.address.address_id = decodeURIComponent(address_detail);
		}

		this.addCartItemsToBackend();
	},
	methods: {
		...mapMutations(['SET_ORDER_TYPE', 'SET_MEMBER']),
		...mapGetters(['isLogin']),
		async addCartItemsToBackend() {
			if (!this.cart.length) return; 

			uni.showLoading({ title: '同步购物车中' });
			try {
				this.cart_ids = []; 
				for (const item of this.cart) {
					const data = {
						goods_id: item.id,
						num: item.number,
						type: 0
					};
					const response = await this.$u.api.addOrderCart(data);
					if (response && response.cart_id) {
						this.cart_ids.push(response.cart_id);
						console.log('Cart ID added:', response.cart_id);
					}
				}
				uni.hideLoading();
				// this.$u.toast('购物车同步成功');
			} catch (error) {
				uni.hideLoading();
				this.$u.toast('加入购物车失败，请返回重新选择');
				// console.error('Error adding cart items:', error);
			}
		},
		async getUserInfo() {
			if (this.isLogin) {
				let data = await this.$u.api.userGetUserInfo();
				if (data) {
					this.SET_MEMBER({ ...this.member, money: data.money });
					if (data.name) this.address.name = data.name;
					if (data.mobile) this.address.mobile = data.mobile;
				}
			}
		},
		fillContact() {
			if (this.isLogin) {
				let data = this.member;
				if (data.name) this.address.name = data.name;
				if (data.mobile) this.address.mobile = data.mobile;
			}
		},
		setPayType(paytype) {
			if (paytype === 2 && this.member.money < this.amount) {
				this.$u.toast('余额不足，请选择其他支付方式');
				return;
			}
			this.payType = paytype;
			uni.setStorageSync('paytype', paytype);
		},

		goToRemark() {
			uni.navigateTo({
				url: '/pages/components/pages/remark/remark?remark=' + encodeURIComponent(this.form.remark)
			});
		},
		scanToGetAddress() {
			let that = this;
			that.address.address_id = '';
			uni.scanCode({
				onlyFromCamera: true,
				scanType: ['barCode', 'qrCode'],
				success: function(res) {
					try {
						let bedParam = '';
						let hospitalId = null;
						if (res.result.includes('?')) {
							const urlParts = res.result.split('?');
							if (urlParts.length > 1) {
								const params = urlParts[1].split('&');
								for (const param of params) {
									if (param.startsWith('bed=')) {
										bedParam = param.substring(4);
									} else if (param.startsWith('hospital_id=')) {
										hospitalId = param.substring(12);
									}
								}
							}
						}
						if (hospitalId && hospitalId !== that.store.hospital_id) {
							that.$u.toast('扫码地址非本院区，请重新选择商品');
							return;
						}
						
						if (bedParam) {
							that.address.scanAddress = decodeURIComponent(bedParam);
							that.address.address_id = decodeURIComponent(bedParam);
						} else {
							that.$u.toast('未找到床位信息');
						}
					} catch (e) {
						console.error('Scan error:', e);
					}
				},
				fail: function() {
					that.$u.toast('扫码失败');
				}
			});
		},
		submit() {
			if (!this.address.name) {
				this.$u.toast('请输入姓名');
				return;
			}
			if (!this.address.mobile) {
				this.$u.toast('请输入手机号');
				return;
			}
			if (!this.address.address_id) {
				this.$u.toast('请扫码获取地址');
				return;
			}
			if (!this.cart.length || !this.cart_ids.length) {
				this.$u.toast('提交失败，请重新下单');
				return;
			}
			this.ensureAddressModalVisible = true;
		},
		async pay() {
			uni.showLoading({ title: '加载中' });
			try {
				const data = {
					cart_ids: this.cart_ids.join(','), // 逗号分隔的 cart_ids
					address_id: this.address.address_id,
					order_remark: this.form.remark || '',
					pay_type: this.payType, // 1=微信支付, 2=余额支付
					type: this.orderType === 'takeout' ? 2 : 1, // 1=员工, 2=病人
					name: this.address.name,
					tel: this.address.mobile
				};

				console.log('Submitting order:', data);
				let order = await this.$u.api.orderSubmit(data);
				console.log('Order response:', order);

				if (!order) {
					throw new Error(order.msg || '订单创建失败');
				}
				if (!order || !order.order_no) {
					throw new Error('订单号缺失');
				}

				// 根据 pay_type 和后端响应处理
				if (this.payType === 1) {
					// 微信支付：调用 payOrder 获取支付参数
					await this.weixinPay(order.order_no);
				} else if (this.payType === 2) {
					// 余额支付：后端已处理，检查 pay_status
					if (order.pay_status === "1") {

						// 支付已完成（后端 balance_pay 成功）
						this.handlePaymentSuccess();
					
						// 余额不足后端直接微信支付，无需前端处理
					// } else if (order.pay_code === 202) {
						// 余额不足，切换到微信支付
						// this.$u.toast('余额不足，切换到微信支付');
						// await this.weixinPay(order.order_no);

						// 后端未完成支付，换到微信支付
					} else {
						await this.weixinPay(order.order_no);
					}
				}
			} catch (error) {
				console.error('Pay error:', data);
				this.$u.toast(error.data.info || '操作失败，请重试');
			} finally {
				uni.hideLoading();
			}
		},
		async balancePay(orderNo) {
			try {
				console.log('Initiating balance payment for order:', orderNo);
				let pay = await this.$u.api.payBalance({ order_no: orderNo });
				console.log('Balance pay response:', pay);

				if (!pay || pay.code !== 200) {
					throw new Error(pay.msg || '余额支付失败');
				}
				if (pay.data.pay_code === 202) {
					// 余额不足，切换到微信支付
					this.$u.toast('余额不足，切换到微信支付');
					await this.weixinPay(orderNo);
					return;
				}

				this.handlePaymentSuccess();
			} catch (error) {
				console.error('Balance pay error:', error);
				throw new Error(error.message || '余额支付失败');
			}
		},
		async weixinPay(orderNo) {
			try {
				let data = await this.$u.api.payUnify({
					order_no: orderNo,
					pay_type: 1,
					name: this.address.name,
					tel: this.address.mobile,
					address_id: this.address.address_id,
					order_remark: this.form.remark || ''
				});

				if (!data) {
					throw new Error(data.msg || '微信支付调用失败');
				}

				if (!data.timeStamp || !data.nonceStr || !data.package || !data.paySign) {
					throw new Error('微信支付参数缺失');
				}

				// 唤起微信支付
				await new Promise((resolve, reject) => {
					// #ifdef MP-WEIXIN
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.package,
						signType: 'MD5',
						paySign: data.paySign,
						success: (res) => {
							this.handlePaymentSuccess();
							resolve(res);
						},
						fail: (err) => {
                    console.error('WeChat payment failed:', err);
						// 用户取消支付的情况
						if (err.errMsg.includes('cancel')) {
							this.$u.toast('支付已取消');
							reject(new Error('支付已取消'));
							uni.switchTab({
								url: '/pages/take-foods/take-foods'
							});
							} else {
								this.$u.toast('支付失败，请重试');
								reject(new Error('支付失败: ' + (err.errMsg || '')));
								uni.switchTab({
									url: '/pages/take-foods/take-foods'
								});
							}
						},
						complete: (res) => {
							console.log('WeChat payment complete:', res);
						}
					});
					// #endif

					// #ifdef H5
					if (data.trade_type === 'MWEB') {
						console.log('Redirecting to MWEB payment:', data.mweb_url);
						location.href = data.mweb_url;
						resolve();
					} else if (data.trade_type === 'JSAPI') {
						this.$u.api.payJssdkBuildConfig().then(config => {
							console.log('JSSDK config:', config);
							if (!config) {
								throw new Error('支付配置失败');
							}
							jweixin.config(config);
							jweixin.ready(() => {
								jweixin.chooseWXPay({
									timestamp: data.timeStamp,
									nonceStr: data.nonceStr,
									package: 'prepay_id=' + data.prepay_id,
									signType: 'MD5',
									paySign: data.paySign,
									success: (res) => {
										console.log('H5 WeChat payment successful:', res);
										this.handlePaymentSuccess();
										resolve(res);
									},
									fail: (err) => {
										console.error('H5 WeChat payment failed:', err);
										reject(new Error('支付失败: ' + (err.errMsg || '')));
									},
									complete: (res) => {
										console.log('H5 WeChat payment complete:', res);
									}
								});
							});
							jweixin.error((res) => {
								console.error('JSSDK error:', res);
								reject(new Error('支付配置失败'));
							});
						});
					} else {
						throw new Error('不支持的微信支付类型');
					}
					// #endif
				});
			} catch (error) {
				console.error('WeChat pay error:', error);
				throw new Error(error.message || '微信支付调用失败');
			}
		},
		handlePaymentSuccess() {
			// 支付成功后的统一处理
			this.SET_MEMBER({ ...this.member, money: this.member.money - (this.payType === 2 ? this.amount : 0) });
			uni.removeStorageSync('cart');
			this.$u.toast('支付成功');
			uni.switchTab({
				url: '/pages/take-foods/take-foods'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
	}
	.arrow {
		width: 50rpx;
		height: 50rpx;
		position: relative;
		margin-right: -10rpx;
	}
	.location {
		.store-name {
			font-size: $font-size-lg;
		}
		.iconfont {
			font-size: 50rpx;
			line-height: 100%;
			color: $color-primary;
		}
	}
	.section-1 {
		margin-bottom: 30rpx;
		.contact {
			.contact-tip {
				margin-left: 10rpx;
				border: 2rpx solid $color-primary;
				padding: 6rpx 10rpx;
				color: $color-primary;
			}
		}
	}
	.section-2 {
		.name-and-props {
			width: 65%;
		}
	}
	.payment {
		margin-bottom: 30rpx;
		.disabled {
			color: $text-color-grey;
		}
		.payment-icon {
			font-size: 44rpx;
			margin-right: 10rpx;
		}
		.checkbox {
			font-size: 36rpx;
			margin-left: 10rpx;
		}
		.checked {
			color: $color-primary;
		}
	}
	.pay-box {
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
		height: 100rpx;
	}
	.modal-content {
		.change-address-btn {
			line-height: 2;
			padding: 0 1em;
		}
		.pay_btn {
			width: 100%;
			border-radius: 50rem !important;
			line-height: 3;
		}
	}
	.choice {
		background-color: $bg-color-grey;
		border-radius: 38rpx;
		display: flex;
		align-items: center;
		font-size: $font-size-sm;
		padding: 0 38rpx;
		color: $text-color-assist;
		.dinein,
		.takeout {
			width: 50%;
			position: relative;
			display: flex;
			align-items: center;
			&.active {
				padding: 14rpx 38rpx;
				color: #ffffff;
				background-color: $color-primary;
				border-radius: 38rpx;
			}
		}
		.takeout {
			margin-left: 20rpx;
			height: 100%;
			flex: 1;
			padding: 14rpx 0;
		}
	}
	.address-section {
		.scan-tip {
			font-size: $font-size-base;
			color: $text-color-assist;
		}
		.input {
			flex: 1;
			padding: 10rpx;
			border: 1px solid #ccc;
			border-radius: 8rpx;
		}
	}
	.scan-icon {
		width: 40rpx;
		height: 40rpx;
	}
	.scan-icon-left {
		width: 50rpx;
		height: 50rpx;
	}
	.scan-btn {
		border: none !important;
		background: #fff;
	}
</style>
